package com.tomcat.myapplication.http;

import android.content.Context;

import com.tomcat.myapplication.http.constants.ConstantRequestURL;
import com.tomcat.myapplication.http.i_http.HttpService;

import java.io.IOException;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.CertificateFactory;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManagerFactory;

import okhttp3.OkHttpClient;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class HttpRetrofit extends HttpSubscribe {
    private String BASE_URL = "";
    private HttpService mHttpService = null;
    private Retrofit retrofit = null;
    private OkHttpClient okHttpClient = null;
    private Context mContext;
    private String mType;

    /**
     * 初始化Retrofi获取HttpCrmService
     */
    public void init(Context context, String type) {
        this.mType = type;
        mContext = null;
        okHttpClient = null;
        retrofit = null ;
        mHttpService = null;
        try {
            InputStream inputStream = new Buffer().writeUtf8(ConstantRequestURL.CER).inputStream();
            setCertificates(inputStream);
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (mContext == null) {
            this.mContext = context;
        }

        if (okHttpClient == null || retrofit == null) {

            BASE_URL = ConstantRequestURL.BASE_URL;
            //初始化Retrofit
            initRetrofit(type);
        }

        if (mHttpService == null) {
            mHttpService = retrofit.create(HttpService.class);
        }
    }
    /**
     * 初始化Retrofit
     * @param type
     */
    private void initRetrofit(String type) {
        try {
            //获取网络连接
            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            HttpInterceptor httpInterceptor = new HttpInterceptor(mContext,type);

            //添加拦截器
            builder.addInterceptor(httpInterceptor);

            //设置超时
            builder.connectTimeout(30, TimeUnit.SECONDS);
            builder.readTimeout(40, TimeUnit.SECONDS);
            builder.writeTimeout(40, TimeUnit.SECONDS);
            //错误重连
            builder.retryOnConnectionFailure(true);
            okHttpClient = builder.build();

            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
        } catch (Exception e) {
            System.out.print("");
        }
    }

    /**
     * 获取HttpService
     *
     */
    public HttpService getService() {
        if (mHttpService == null && retrofit != null) {
            mHttpService = retrofit.create(HttpService.class);
        }
        return mHttpService;
    }

    public void setCertificates(InputStream... certificates) {
        try {
            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
            keyStore.load(null);
            int index = 0;
            for (InputStream certificate : certificates) {
                String certificateAlias = Integer.toString(index++);
                keyStore.setCertificateEntry(certificateAlias, certificateFactory.generateCertificate(certificate));

                try {
                    if (certificate != null)
                        certificate.close();
                } catch (IOException e) {
                }
            }

            SSLContext sslContext = SSLContext.getInstance("TLS");

            TrustManagerFactory trustManagerFactory =
                    TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());

            trustManagerFactory.init(keyStore);
            sslContext.init
                    (
                            null,
                            trustManagerFactory.getTrustManagers(),
                            new SecureRandom()
                    );
            //.setSslSocketFactory(sslContext.getSocketFactory());


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
